package com.zgh.init;//package com.zgh.init;
//
//import java.text.ParseException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import javax.annotation.PostConstruct;
//
//import org.quartz.CronTrigger;
//import org.quartz.Job;
//import org.quartz.JobDetail;
//import org.quartz.JobExecutionContext;
//import org.quartz.JobExecutionException;
//import org.quartz.JobKey;
//import org.quartz.SchedulerException;
//import org.quartz.SimpleTrigger;
//import org.quartz.Trigger;
//import org.quartz.TriggerKey;
//import org.quartz.impl.JobDetailImpl;
//import org.quartz.impl.triggers.CronTriggerImpl;
//import org.quartz.impl.triggers.SimpleTriggerImpl;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.BeansException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.ApplicationContextAware;
//import org.springframework.scheduling.quartz.SchedulerFactoryBean;
//import org.springframework.stereotype.Service;
//
//import com.f2bpm.base.core.utils.AppUtil;
//import com.xxg.base.module.PageData;
//import com.xxg.base.quartz.BaseTask;
//import com.xxg.util.SystemConstant;
//import com.xxg.util.SystemProperty;
//import com.zgh.manager.IManagerService;
//import com.zgh.manager.module.AutoTask;
//import com.zgh.manager.module.HandTask;
//import com.zgh.manager.module.SystemConfig;
//
//
//@Service
//public class InitService implements ApplicationContextAware, Job {
//
//    private static final Logger LOGGGER = LoggerFactory.getLogger(InitService.class);
//
//    private static final String SYSTEM_NAME = SystemProperty.getProperty("systemName");
//    private static final String SYSTEM_CODE = SystemProperty.getProperty("systemCode");
//    private static final int CLUSTER_NODE = Integer.parseInt(SystemProperty.getProperty("clusterNode"));
//
//    @Autowired
//    private IManagerService managerService;
//
//    @Autowired
//    private SchedulerFactoryBean schedulerFactoryBean;
//
//    @Autowired
//    private ApplicationContext applicationContext;
//
//
//    @Override
//    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
//        this.applicationContext = arg0;
//        AppUtil.setApplicationContext(arg0);
//    }
//
//
//    @PostConstruct
//    public void init() throws Exception {
//        //loadSystemPropertiesFromManager();
//       if(CLUSTER_NODE==1){
//        	startQuartzTask();
//       }
//    }
//
//    private void loadSystemPropertiesFromManager() throws Exception {
//        List<SystemConfig> list = new ArrayList<SystemConfig>();
//
//        //获取通用配置，不管集群节点
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("systemName", SYSTEM_NAME);
//        params.put("systemCode", SYSTEM_CODE);
//        params.put("clusterNode", 0);
//        PageData pageData = new PageData();
//        pageData.setPageSize(PageData.MAX_PAGE_SIZE);
//        List<SystemConfig> temp = managerService.listSystemConfig(params, pageData);
//        if (temp != null && !temp.isEmpty()) {
//            list.addAll(temp);
//        }
//
//        //获取特殊配置
//        if (CLUSTER_NODE > 0) {
//            params.put("clusterNode", CLUSTER_NODE);
//            temp = managerService.listSystemConfig(params, pageData);
//            if (temp != null && !temp.isEmpty()) {
//                list.addAll(temp);
//            }
//        }
//
//
//        if (list == null || list.isEmpty()) {
//            return;
//        }
//
//        Map<String, String> map = new HashMap<String, String>();
//        for (SystemConfig sc : list) {
//            //忽略以下四个配置
//            if ("systemName".equals(sc.getConfigName())) {
//                continue;
//            }
//            if ("systemCode".equals(sc.getConfigName())) {
//                continue;
//            }
//            if ("ifCluster".equals(sc.getConfigName())) {
//                continue;
//            }
//            if ("clusterNode".equals(sc.getConfigName())) {
//                continue;
//            }
//            map.put(sc.getConfigName(), sc.getConfigValue());
//        }
//        SystemProperty.setMap(map);
//
//    }
//
//
//    private void startQuartzTask() throws Exception {
//        //1分钟执行1次,无限重复
////      SimpleTrigger simpleTrigger = new SimpleTriggerImpl(InitService.class.getName(), SYSTEM_NAME, SimpleTrigger.REPEAT_INDEFINITELY, 60000L);
////      JobDetail jobDetail = new JobDetailImpl(InitService.class.getName(), SYSTEM_NAME, BaseTask.class);
////      jobDetail.getJobDataMap().put("job", this);
////      schedulerFactoryBean.getScheduler().scheduleJob(jobDetail, simpleTrigger);
//
//        //下载用户及工会、单位数据
//        CronTrigger downloadUserTask=new CronTriggerImpl("DownloadUserTask", SYSTEM_NAME, "0 0/1 * * * ?");
//        JobDetail downloadUserTaskJobDetail = new JobDetailImpl("DownloadUserTask", SYSTEM_NAME, BaseTask.class);
//        Job downloadUserTaskJob = (Job) applicationContext.getBean("DownloadUserTask");
//        downloadUserTaskJobDetail.getJobDataMap().put("job", downloadUserTaskJob);
//        schedulerFactoryBean.getScheduler().scheduleJob(downloadUserTaskJobDetail, downloadUserTask);
//   }
//
//
//    @Override
//    public void execute(JobExecutionContext context)
//            throws JobExecutionException {
//        try {
//            //refreshTask();
//        } catch (Exception ex) {
//            LOGGGER.error("自动任务启动失败", ex);
//        }
//    }
//
//
//    private void refreshTask() throws ParseException, NumberFormatException, SchedulerException {
//        List<AutoTask> list = new ArrayList<AutoTask>();
//
//        //获取普通任务
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("systemName", SYSTEM_NAME);
//        params.put("systemCode", SYSTEM_CODE);
//        params.put("clusterNode", 0);
//        PageData pageData = new PageData();
//        pageData.setPageSize(PageData.MAX_PAGE_SIZE);
//        List<AutoTask> temp = managerService.listAutoTask(params, pageData);
//
//        if (temp != null && !temp.isEmpty()) {
//            list.addAll(temp);
//        }
//
//        //获取特殊的任务
//        if (CLUSTER_NODE > 0) {
//            params.put("clusterNode", CLUSTER_NODE);
//            temp = managerService.listAutoTask(params, pageData);
//            if (temp != null && !temp.isEmpty()) {
//                list.addAll(temp);
//            }
//        }
//
//        for (AutoTask task : list) {
//
//            Job job = null;
//            try {
//                job = (Job) applicationContext.getBean(task.getTaskName());
//            } catch (BeansException ex) {
//                //如果任务没有配置，忽略
//                LOGGGER.error("自动任务不存在:" + task.getTaskName());
//                continue;
//            }
//
//            //自动任务
//            JobKey jobKey = new JobKey(task.getTaskName(), SYSTEM_NAME);
//            TriggerKey triggerKey = new TriggerKey(task.getTaskName(), SYSTEM_NAME);
//
//            //最新的调度参数
//            Trigger newTrigger = null;
//            if (AutoTask.TASK_DISPATCH_MODE_INTERVAL.equals(task.getDispatchMode())) {
//                newTrigger = new SimpleTriggerImpl(task.getTaskName(), SYSTEM_NAME,
//                        SimpleTrigger.REPEAT_INDEFINITELY, Long.parseLong(task.getDispatchParams()));
//            } else if (AutoTask.TASK_DISPATCH_MODE_TIMER.equals(task.getDispatchMode())) {
//                newTrigger = new CronTriggerImpl(task.getTaskName(), SYSTEM_NAME, task.getDispatchParams());
//            }
//
//
//            if (schedulerFactoryBean.getScheduler().getJobDetail(jobKey) == null) {//如果任务没有加入调度中
//                if (SystemConstant.NORMAL_STRING.equals(task.getStatus())) {
//                    if (AutoTask.TASK_DISPATCH_MODE_INTERVAL.equals(task.getDispatchMode())
//                            || AutoTask.TASK_DISPATCH_MODE_TIMER.equals(task.getDispatchMode())) {
//
//                        JobDetail jobDetail = new JobDetailImpl(task.getTaskName(), SYSTEM_NAME, BaseTask.class);
//                        jobDetail.getJobDataMap().put("job", job);
//                        schedulerFactoryBean.getScheduler().scheduleJob(jobDetail, newTrigger);
//                    }
//                }
//            } else {
//                //如果任务已经在调度，看是否要删除任务
//                if (!SystemConstant.NORMAL_STRING.equals(task.getStatus())) {
//                    schedulerFactoryBean.getScheduler().deleteJob(jobKey);
//                } else {
//                    //是否要更新调度参数
//                    Trigger oldTrigger = schedulerFactoryBean.getScheduler().getTrigger(triggerKey);
//                    if (oldTrigger instanceof SimpleTrigger) {
//                        SimpleTrigger st = (SimpleTrigger) oldTrigger;
//                        if (AutoTask.TASK_DISPATCH_MODE_INTERVAL.equals(task.getDispatchMode())
//                                && st.getRepeatInterval() == Long.parseLong(task.getDispatchParams())) {
//                            //调度参数未变，无须动作
//                        } else {
//                            //调度参数改变，重新调度
//                            schedulerFactoryBean.getScheduler().deleteJob(jobKey);
//                            JobDetail jobDetail = new JobDetailImpl(task.getTaskName(), SYSTEM_NAME, BaseTask.class);
//                            jobDetail.getJobDataMap().put("job", job);
//                            schedulerFactoryBean.getScheduler().scheduleJob(jobDetail, newTrigger);
//
//                        }
//                    }
//
//                    if (oldTrigger instanceof CronTrigger) {
//                        CronTrigger ct = (CronTrigger) oldTrigger;
//                        if (AutoTask.TASK_DISPATCH_MODE_TIMER.equals(task.getDispatchMode())
//                                && ct.getCronExpression().equals(task.getDispatchParams())) {
//                            //调度参数未变，无须动作
//                        } else {
//                            //调度参数改变，重新调度
//                            schedulerFactoryBean.getScheduler().deleteJob(jobKey);
//                            JobDetail jobDetail = new JobDetailImpl(task.getTaskName(), SYSTEM_NAME, BaseTask.class);
//                            jobDetail.getJobDataMap().put("job", job);
//                            schedulerFactoryBean.getScheduler().scheduleJob(jobDetail, newTrigger);
//                        }
//                    }
//
//                }
//
//            }
//
//            //查询是否有手动启动任务的命令
//            HandTask taskManualStart = managerService.getLastHandTask(SYSTEM_NAME, SYSTEM_CODE, CLUSTER_NODE, task.getTaskName());
//            if (taskManualStart != null) {
//                JobKey key = new JobKey("临时" + task.getTaskName(), SYSTEM_NAME);
//                if (schedulerFactoryBean.getScheduler().getJobDetail(key) != null) {
//                    //已经有手动启动了
//                    continue;
//                }
//                Trigger trigger = new SimpleTriggerImpl("临时" + task.getTaskName(), SYSTEM_NAME, 0, 1000L);
//                JobDetail jobDetail = new JobDetailImpl("临时" + task.getTaskName(), SYSTEM_NAME, BaseTask.class);
//                jobDetail.getJobDataMap().put("job", job);
//                schedulerFactoryBean.getScheduler().scheduleJob(jobDetail, trigger);
//            }
//        }
//    }
//
//}
